package work.mediway.common.aop;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mediway.hos.base.exception.BaseBusinessException;
import com.mediway.hos.base.model.BaseResponse;
import com.mediway.hos.common.util.CommonUtils;
import com.mediway.hos.i18n.constant.I18nConstant;
import com.mediway.hos.i18n.service.I18nStaticTranslationService;
import com.mediway.hos.i18n.utils.HosI18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import work.mediway.common.exception.GlobalDataException;

import java.util.Collection;
import java.util.List;

/**
 * 国际化处理
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/4/22
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class CdrI18nAspect {
    /**
     * 切入点，拦截所有controller的方法
     */
    @Pointcut("execution(* work.mediway..*.controller..*.*(..))")
    private void pointcut() {}

    @Autowired
    private I18nStaticTranslationService staticTranslationService;

    /**
     * 切面处理方法
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("pointcut()")
    private Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 先判断有没有开启国际化
        boolean openI18n = HosI18nUtil.isOpenI18n();
        // 未开启直接结束
        if (!openI18n){
            return pjp.proceed();
        }
        // 当前请求header中的语种 没有取默认的
        String defaultLanguage = I18nConstant.I18N_DEFAULT_LANGUAGE;
        String language = HosI18nUtil.getRequestLanguage();
        Object result;

        try {
            result= pjp.proceed();
        } catch (BaseBusinessException be) {
            be.printStackTrace();
            String msg = be.getMessage();
            // 判断是否需要拦截进行翻译，true-拦截翻译，false-不拦截，自行翻译
            if (be.getIsIntercept()) {
                // 根据code对自定义异常的Message进行翻译
                msg = staticTranslationService.queryTransByResponseCode(be.getCode(),be.getMessage(), defaultLanguage, language);

            }
            return BaseResponse.error(StrUtil.isBlank(be.getCode()) ? StrUtil.toStringOrNull(HttpStatus.HTTP_INTERNAL_ERROR) : be.getCode(), msg);
        }catch (GlobalDataException e){
            e.printStackTrace();
            String msg = e.getMessage();
                // 根据code对自定义异常的Message进行翻译
                msg = staticTranslationService.queryTransByResponseCode(String.valueOf(e.getCode()),e.getMessage(), defaultLanguage, language);

            return BaseResponse.error(ObjectUtil.isEmpty(e.getCode()) ? StrUtil.toStringOrNull(HttpStatus.HTTP_INTERNAL_ERROR) : e.getCode(), msg);
        }
            /*catch (Exception e){
            e.printStackTrace();
            String code = SysExceptionEnum.BUSINESS_EXE_ERROR.getCode();
            String msg = staticTranslationService.queryTransByResponseCode(code,null, defaultLanguage, language);
            return BaseResponse.error(code, msg);
        }*/


        if (result instanceof BaseResponse){
            BaseResponse baseResponse = (BaseResponse) result;
            if (CommonUtils.isNull(baseResponse)) {
                return result;
            }
            String msg = baseResponse.getMsg();
            // 判断是否需要拦截进行翻译，true 或者 null-拦截翻译，false-不拦截，自行翻译
            Boolean isIntercept = baseResponse.getIsIntercept();
            if (CommonUtils.isNull(isIntercept) || isIntercept) {
                // 根据code对Response的msg进行翻译
                msg = staticTranslationService.queryTransByResponseCode(baseResponse.getCode(),baseResponse.getMsg(), defaultLanguage, language);
            }
            baseResponse.setMsg(msg);

            //对Response的data进行翻译
            transBaseResponseData(baseResponse);

        }
        return result;
    }

    /**
     * 翻译返回数据
     * @param baseResponse
     */
    private void  transBaseResponseData(BaseResponse baseResponse){
        Object data = baseResponse.getData();
        if (ObjectUtil.isNotNull(data)) {
            // 处理数据
            if (ClassUtil.isBasicType(data.getClass()) || ClassUtil.isSimpleTypeOrArray(data.getClass())) {
                // 基本类型切面不做处理（如果需要请手动处理）
            } else if (data instanceof IPage) {
                IPage rr = (IPage) data;
                List<?> list = (List<?>) rr.getRecords();
                HosI18nUtil.autoTranslateList(list);
                rr.setRecords(list);
            } else if (data instanceof Collection){
                Collection<?> list = (Collection<?>) data;
                HosI18nUtil.autoTranslateList(list);
                baseResponse.setData(list);
            } else {
                HosI18nUtil.autoTranslateObject(data);
            }
            baseResponse.setData(data);
        }
    }
}
